package com.hzdesk.media.koreabatchmatvector.utils;

import android.annotation.SuppressLint;
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.LinkProperties;
import android.net.Network;
import android.net.NetworkInfo;
import android.os.Build;
import android.support.annotation.RequiresApi;
import android.util.Log;

import java.io.BufferedReader;
import java.io.Closeable;
import java.io.DataOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.InterfaceAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;

/**
 * Created by Administrator on 2018/8/4.
 * 杭州席媒科技有限公司  Developers  刘传华  10
 * 佛祖镇楼 bug辟易
 */

public class IpUtils {
    /**
     * 得到有限网关的IP地址
     *
     * @return
     */
    @SuppressLint("LongLogTag")
    public static String getLocalIp() {

        try {
            // 获取本地设备的所有网络接口
            Enumeration<NetworkInterface> enumerationNi = NetworkInterface.getNetworkInterfaces();
            while (enumerationNi.hasMoreElements()) {
                NetworkInterface networkInterface = enumerationNi.nextElement();
                String interfaceName = networkInterface.getDisplayName();
                Log.i("tag", "网络名字" + interfaceName);

                // 如果是有限网卡
                if (interfaceName.equals("eth0")) {
                    Enumeration<InetAddress> enumIpAddr = networkInterface.getInetAddresses();
                    while (enumIpAddr.hasMoreElements()) {
                        // 返回枚举集合中的下一个IP地址信息
                        InetAddress inetAddress = enumIpAddr.nextElement();
                        // 不是回环地址，并且是ipv4的地址
                        if (!inetAddress.isLoopbackAddress() && inetAddress instanceof Inet4Address) {
                            Log.i("tag", inetAddress.getHostAddress() + "   ");
                            return inetAddress.getHostAddress();
                        }
                    }
                }
            }

        } catch (SocketException e) {
            e.printStackTrace();
        }
        return "0.0.0.0";

    }

    /**
     * @desc 获取mac
     * */
    public static String loadFileAsString(String filePath) throws java.io.IOException{
        StringBuffer fileData = new StringBuffer(1000);
        BufferedReader reader = new BufferedReader(new FileReader(filePath));
        char[] buf = new char[1024];
        int numRead=0;
        while((numRead=reader.read(buf)) != -1){
            String readData = String.valueOf(buf, 0, numRead);
            fileData.append(readData);
        }
        reader.close();
        return fileData.toString();
    }

    /*
    * Get the STB MacAddress
    */
    public static String getMacAddress(){
        try {
            return loadFileAsString("/sys/class/net/eth0/address").toUpperCase().substring(0, 17);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }
    /**
     * @desc 获取dns
     * */
    @SuppressLint("LongLogTag")
    @RequiresApi(api = Build.VERSION_CODES.M)
    public static String getDns(Context mContext){
        ConnectivityManager connManager = (ConnectivityManager)mContext.getSystemService(Context.CONNECTIVITY_SERVICE);
        Network mNetworkInfor =  connManager.getActiveNetwork();
        LinkProperties mlist = connManager.getLinkProperties(mNetworkInfor);
        List<InetAddress> mbean = mlist.getDnsServers();
        for (InetAddress inetAddress : mbean) {
            if (!inetAddress.isLoopbackAddress   () && inetAddress instanceof Inet4Address) {
                return    inetAddress.getHostAddress();
            }
        }
        return "";
    }

    @SuppressLint("LongLogTag")
    public static String getGateWay(Context mContext) {

        return "";
    }
    public static String getRoot(String paramString) {
        StringBuilder result = new StringBuilder();
        Process process = null;
        DataOutputStream os = null;
        BufferedReader bufrIn = null;
        BufferedReader bufrError = null;
        try {
            // 执行命令, 返回一个子进程对象（命令在子进程中执行）
            process = Runtime.getRuntime().exec("su");
            os = new DataOutputStream(process.getOutputStream());
            os.writeBytes(paramString + "\n");
            os.writeBytes("exit\n");
            os.flush();
            // 方法阻塞, 等待命令执行完成（成功会返回0）
            process.waitFor();
            // 获取命令执行结果, 有两个结果: 正常的输出 和 错误的输出（PS: 子进程的输出就是主进程的输入）
            bufrIn = new BufferedReader(new InputStreamReader(process.getInputStream(), "UTF-8"));
            bufrError = new BufferedReader(new InputStreamReader(process.getErrorStream(), "UTF-8"));
            // 读取输出
            String line = null;
            while ((line = bufrIn.readLine()) != null) {
                result.append(line).append('\n');
            }
            while ((line = bufrError.readLine()) != null) {
                result.append(line).append('\n');
            }
        } catch (Exception localException) {
            System.out.println("@@@@root cmd error:" + localException);
            //localException.printStackTrace();
            return "false";
        } finally {
            try {
                closeStream(bufrIn);
                closeStream(bufrError);
                closeStream(os);
                // 销毁子进程
                if (process != null) {
                    process.destroy();
                }
            } catch (Exception e) {
                System.out.println("###root cmd error:" + e);
            }
        }
        // 返回执行结果
        return result.toString();
    }
    private static void closeStream(Closeable stream) {
        if (stream != null) {
            try {
                stream.close();
            } catch (Exception e) {
                // nothing
            }
        }
    }
}
